package controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.bican.wordpress.Wordpress;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import redstone.xmlrpc.XmlRpcFault;
import server.Image;
import server.PostBlogger;
import server.PostCustomUrl;
import server.PostWp;

import com.google.gdata.util.ServiceException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class GetSpecialContentServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if (dbObject == null) {
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String blog = (String) session.getAttribute("work");
		if(blog==null)
		{
			try {
				response.sendRedirect("/manager-blog");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		DBCollection collection = Data.data("urlCraw");
		DBCursor cursor = collection.find(new BasicDBObject("username",
				dbObject.get("username")).append("blogurl", blog));
		request.setAttribute("cursor", cursor);

		String[] listError = new String[5];
		request.setAttribute("listError", listError);

		DBCollection coll = Data.data("blogCraw");
		DBObject object = coll.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		
		if(object.get("type").toString().equals("wordpress"))
		{
			ArrayList<String> category = Utils.returnCategory(object);
			request.setAttribute("category", category);
		}
		request.setAttribute("object", object);
		try {
			request.getRequestDispatcher("/get_special_content.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String blog = (String) session.getAttribute("work");
		
		if(blog==null)
		{
			try {
				response.sendRedirect("/manager-blog");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		DBCollection collection = Data.data("urlCraw");
		DBCursor cursor = collection.find(new BasicDBObject("username",
				dbObject.get("username")).append("blogurl", blog));
		request.setAttribute("cursor", cursor);
		
		String sitemap = request.getParameter("sitemap");
		
		String regtitle = request.getParameter("regtitle");
		String regcontent = request.getParameter("regcontent");
		String regremove = request.getParameter("regremove");
		
		String typeLink = request.getParameter("typeLink");
		String source = request.getParameter("source");
		String source_type = request.getParameter("source_type");
		String category = request.getParameter("category");
		String sumtitlebefore = request.getParameter("sumtitlebefore");
		String sumtitleafter = request.getParameter("sumtitleafter");
		String language = request.getParameter("language");
		String translate = request.getParameter("translate");
		String rewriter_title = request.getParameter("rewriter_title");
		System.out.println(category);
		sitemap = Utils.fomatSitemap(sitemap);
		String charset="UTF-8";
		String source_image = request.getParameter("source_image");
		String remove_tag_a = request.getParameter("remove_tag_a");
		
		String[] listError = new String[5];
		if(sitemap!=null&&sitemap.equals(""))
			listError[0]="Url is not empty !";
		if(regtitle!=null&&regtitle.equals(""))
			listError[2]="Regexp title  is not empty !";
		if(regcontent!=null&&regcontent.equals(""))
			listError[3]="Regexp content is not empty !";
		
		DBCollection coll = Data.data("blogCraw");
		DBObject object = coll.findOne(new BasicDBObject("username",dbObject.get("username")).append("blogurl", blog));
		
		if(object.get("type").toString().equals("wordpress"))
		{
			ArrayList<String> categoryss = Utils.returnCategory(object);
			request.setAttribute("category", categoryss);
			
			String[] listCategory = category.split(",");
			for (int i = 0; i < listCategory.length; i++) {
				int k=0;
				for (int j = 0; j < categoryss.size(); j++) {
					if(categoryss.get(j).equals(listCategory[i]))
					{
						k=1;
					}
				}
				if(k==0)
				{
					String username = object.get("usernameblog").toString();
				    String password = object.get("passwordblog").toString();
				    String xmlRpcUrl = object.get("blogurl").toString()+"/xmlrpc.php";
				    Wordpress wp = new Wordpress(username, password, xmlRpcUrl);
				    try {
						wp.newCategory(listCategory[i], listCategory[i], 0);
					} catch (XmlRpcFault e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		if(listError[0]==null&&listError[1]==null&&listError[3]==null&&listError[2]==null)
		{
			ArrayList<String> site = Utils.getStachSite();
			
			Document doc=null;
			if(!"yes".equals(translate))
			{
				if(site.contains(Utils.fomatDmain(sitemap)))
				{
					doc = Jsoup.parse(Utils.GetHtml("http://getstackcontent.appspot.com/stack?link="+sitemap, charset));
				} else {
					doc = Jsoup.parse(Utils.GetHtml(sitemap, charset));
				}
				//
				
				
				int index = doc.select("meta").toString().toLowerCase().indexOf("charset=");
				if (index != -1) {
					charset = doc.select("meta").toString().substring(index + 8)
							.replaceAll("[^\\'\\\"0-9a-zA-Z\\-\\_]+[\\w\\W]+", "")
							.replaceAll("[\\'\\\"]+", "");
				}
				//
				if(site.contains(Utils.fomatDmain(sitemap)))
				{
					doc = Jsoup.parse(Utils.GetHtml("http://getstackcontent.appspot.com/stack?link="+sitemap, charset));
				} else {
					doc = Jsoup.parse(Utils.GetHtml(sitemap, charset));
				}
			} else {
				doc = Utils.Translate(sitemap, language);
			}
			String strContent="";
			String ti = "";
			ArrayList<String> term = new ArrayList<String>();
			
			try {
				ti = doc.select(regtitle).text();
				doc = Jsoup.parse(doc.select(regcontent).html());
				String[] remove = regremove.split(" ");
				doc.select("script").remove();
				if (remove.length > 0) {
					for (int i = 0; i < remove.length; i++) {
						try {
							if ((remove[i] != null) && (!remove[i].equals("")))
							{
								String[] reg = remove[i].split("\\|"); 
								
								if(reg.length >=2)
								{
									if(reg[1].equals("last"))
									{
										doc.select(reg[0].replaceAll(">", " ")).last().remove();
									} else {
										doc.select(reg[0].replaceAll(">", " ")).first().remove();
									}
								} else {
									doc.select(remove[i].replaceAll(">", " ")).remove();
								}
							}
						} catch (Exception localException1) {
						}
					}
				}
				
				if(typeLink.equals("nofollow"))
				{
					doc.select("a").attr("rel","nofollow");
				}
				
				strContent = changeImg(doc,sitemap,source_image);
				
				if(remove_tag_a!=null&&remove_tag_a.equals("yes"))
				{
					strContent = Utils.removeTagA(strContent);
				}

				if(source.equals("yes"))
				{
					if(source_type!=null&&source_type.equals("link"))
						strContent += "<br/>Source : <a rel='nofollow' href='"+sitemap+"' target='_blank'>"+sitemap+"</a>";
					else
						strContent += "<br/>Source : "+Utils.fomatDmain(sitemap).replaceAll("[.]{1}", "[dot]");
				}
				
				String message = doc.text();
				term = Utils.returnTag(message);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if("yes".equals(rewriter_title))
			{
				ti = Utils.Spin(ti);
			}
			ti = sumtitlebefore+" "+ti+" "+sumtitleafter;
			ti = ti.trim();
			try {
	        	if(object.get("type").toString().equals("wordpress"))
	        	{
	        		PostWp.postWp(ti, Utils.cleanContent(strContent), term,object,category);
	        		request.setAttribute("success", "Post success");
	        	}
	        	if(object.get("type").toString().equals("blogger"))
	        	{
	        		PostBlogger.postBlogger(ti, Utils.cleanContent(strContent), term,object,category);
	        		request.setAttribute("success", "Post success");
	        	}
	        	if(object.get("type").toString().equals("customurl"))
	        	{
	        		String str = PostCustomUrl.post(ti, Utils.cleanContent(strContent), term,object,category);
	        		if(!"-1".equals(str))
	        			request.setAttribute("success", "Post success");
	        	}
				
				DBCollection collUser = Data.data("users");
				if("yes".equals(translate))
				{
					session.setAttribute("users", collUser.findAndModify(new BasicDBObject("email",dbObject.get("email")),new BasicDBObject("$inc", new BasicDBObject("coin", -1))));
				}
				if("yes".equals(rewriter_title))
				{
					session.setAttribute("users", collUser.findAndModify(new BasicDBObject("email",dbObject.get("email")),new BasicDBObject("$inc", new BasicDBObject("coin", -1))));
				}
				DBCollection collss = Data.data("saveReg");
				DBObject dbObject2 = collss.findOne(new BasicDBObject("domain",Utils.fomatDmain(sitemap)));
				if(dbObject2==null)
				{
					BasicDBObject basicDBObject = new BasicDBObject();
					basicDBObject.put("domain", Utils.fomatDmain(sitemap));
					basicDBObject.put("regtitle", regtitle);
					basicDBObject.put("regcontent", regcontent);
					basicDBObject.put("regremove", regremove);
					collss.insert(basicDBObject);
				}
				
			} catch (XmlRpcFault e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		} else {
			request.setAttribute("sitemap", sitemap);
			request.setAttribute("regtitle", regtitle);
			request.setAttribute("regcontent", regcontent);
			request.setAttribute("regremove", regremove);
		}
		request.setAttribute("listError", listError);
		request.setAttribute("post", "true");
		
		request.setAttribute("object", object);
		
		try {
			request.getRequestDispatcher("/get_special_content.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String changeImg(Document elements,String blogurl,String source_image) throws IOException
	{
		String element = elements.html();
		Elements img = elements.select("img");
		Elements a = elements.select("a");
		element = element.replaceAll("&amp;", "&");
		try {
			for(int i=0;i<a.size();i++)
			{
				String aa= a.eq(i).attr("href");
				if(!"".equals(aa))
				{
					int index = aa.indexOf("&u=");
					int end = aa.indexOf("&usg=");
					String aa1=aa;
	
					if (index != -1) {
						aa1=aa.substring(index+3, end);
					}
					String imageUrl = Utils.fomatLink(aa1, blogurl);
					
					element = element.replace(aa, imageUrl);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			for(int i=0;i<img.size();i++)
			{
				String im= img.eq(i).attr("src");
				if(!"".equals(im))
				{
					String imageUrl = Utils.fomatLink(im, blogurl);

					if(source_image!=null&&source_image.equals("cdn"))
					{
						File file = new File(imageUrl.replaceAll("[ ]{1}", "%20"));  			
						
	
						String path_image="http://cdn.as7.org/";
						
						String file_name = new Random().nextInt(100)+"_"+file.getName().replaceAll("[?]{1}[\\w\\W]*$", "");
						file_name=file_name.replaceAll("[ ]+", "").replaceAll("%20", "").replaceAll("[^\\w.]+", "");
						
						String destinationFile = path_image+file_name;
						
						element = element.replace(im, destinationFile);
					
						try {
							new Image(imageUrl.replaceAll("[ ]{1}", "%20"), file_name);
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						element = element.replace(im, imageUrl);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return element;
	}
}
